package com.pactera.asmp.server.utils;

import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.core.Converter;
import java.util.concurrent.ConcurrentHashMap;
/**
 * @ProjectName: tlsserver
 * @Package com.pactera.asmp.server.utils
 * @ClassName: CacheBeanCopier
 * @Description: 对象值拷贝
 * @Date 2020/06/08 17:29
 * @Author lvzhiqiang
 * @Version 1.0
 */
public class CacheBeanCopier {

    private CacheBeanCopier(){}

    static final ConcurrentHashMap<String, BeanCopier> BEAN_COPIER_MAP = new ConcurrentHashMap<>();

    public static void copy(Object source, Object target) {
        copy(source, target, null);
    }

    public static void copy(Object source, Object target, Converter converter) {
        if (null == source || null == target) {
            return;
        }
        String key = genKey(source, target, converter);
        BeanCopier copier = null;
        if (!BEAN_COPIER_MAP.containsKey(key)) {
            if (null == converter) {
                copier = BeanCopier.create(source.getClass(), target.getClass(), false);
            } else {
                copier = BeanCopier.create(source.getClass(), target.getClass(), true);
            }
            BEAN_COPIER_MAP.putIfAbsent(key, copier);
        } else {
            copier = BEAN_COPIER_MAP.get(key);
        }
        copier.copy(source, target, converter);
    }

    private static String genKey(Object source, Object target, Converter converter) {
        if (null == converter) {
            return source.getClass().getName() + target.getClass().getName();
        }
        return source.getClass().getName() + target.getClass().getName() + converter.getClass().getName();
    }

}
